import os
import sys

import PyQt5
from PyQt5.QtCore import Qt, QThread, pyqtSignal
from llama_index.core.prompts import Prompt
from llama_index.core.settings import Settings
from llama_index.llms.ollama import Ollama
from PyQt5.QtWidgets import QApplication, QDialog, QVBoxLayout, QTextEdit

dirname = os.path.dirname(PyQt5.__file__)
qt_dir = os.path.join(dirname, 'Qt5', 'plugins', 'platforms')
os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = qt_dir

Settings.llm = Ollama(model="gemma3:4b", context_window=2048)
Settings.embed_model = None

prompt = Prompt(
    "你是专业的语言翻译专家，擅长把英文单词或者语句翻译为中文。你的输出应只包含翻译结果，不需要额外解释\n。"
    "你的翻译任务如下\n"
    "英文: {source}\n"
    "中文: "
)


def translate(source: str):
    return Settings.llm.complete(prompt.format(source=source)).text


class TranslateWorker(QThread):
    on_translated = pyqtSignal(str)

    def __init__(self):
        super().__init__()
        self.text = None
        self.require_translate = False

    def translate(self, text):
        self.text = text
        self.require_translate = True

    def run(self):
        while True:
            if not self.require_translate: continue
            try:
                running_text = self.text
                result = translate(running_text)
                if running_text == self.text:
                    self.on_translated.emit(result)
                    self.require_translate = False
            except Exception as e:
                print(e)


class PasteDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("简单翻译器")
        self.resize(500, 300)

        self.setWindowFlags(Qt.Window | Qt.WindowStaysOnTopHint)
        layout = QVBoxLayout(self)
        # 只读的文本编辑器
        self.text_edit = QTextEdit()
        self.text_edit.setPlainText("")
        self.text_edit.setReadOnly(True)
        layout.addWidget(self.text_edit)

    def update_text(self, text):
        self.text_edit.setText(text)


class ClipboardListener:
    def __init__(self):
        self.dialog = PasteDialog()
        self.lipboard = QApplication.clipboard()
        self.lipboard.dataChanged.connect(self.on_clipboard_change)
        self.last_text = ""
        self.worker: TranslateWorker = TranslateWorker()
        self.worker.on_translated.connect(self.dialog.update_text)
        self.worker.start()
        self.dialog.show()

    def on_clipboard_change(self):
        try:
            text = QApplication.clipboard().text().strip()
            if text != self.last_text:
                print("剪贴板更新...")
                self.dialog.update_text("翻译中...")
                self.dialog.show()
                self.worker.translate(text)
                self.last_text = text
            else:
                print("剪贴板内容相同...")
                self.dialog.show()
        except Exception as e:
            print(f"翻译失败: {e}")


if __name__ == "__main__":
    app = QApplication(sys.argv)
    listener = ClipboardListener()
    sys.exit(app.exec_())
